import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { 
  getAIConfig, 
  saveAIConfig, 
  isTokenConfigured, 
  validateToken, 
  getAvailableProviders, 
  getProviderModels 
} from '../services/aiConfigService';
import './AIConfig.css';

const AIConfig = ({ onClose, onConfigSaved }) => {
  const { t } = useTranslation();
  const [config, setConfig] = useState(getAIConfig());
  const [showToken, setShowToken] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const [errors, setErrors] = useState({});
  const [providers] = useState(getAvailableProviders());
  const [models, setModels] = useState(getProviderModels(config.provider));

  useEffect(() => {
    setModels(getProviderModels(config.provider));
  }, [config.provider]);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setConfig(prev => ({ ...prev, [name]: value }));
    
    // Clear error for this field
    if (errors[name]) {
      setErrors(prev => ({ ...prev, [name]: '' }));
    }
  };

  const handleProviderChange = (e) => {
    const provider = e.target.value;
    const providerConfig = providers.find(p => p.id === provider);
    setConfig(prev => ({
      ...prev,
      provider,
      endpoint: providerConfig.endpoint,
      model: getProviderModels(provider)[0]?.id || ''
    }));
    
    // Clear error for this field
    if (errors.provider) {
      setErrors(prev => ({ ...prev, provider: '' }));
    }
  };

  const validateForm = () => {
    const newErrors = {};
    
    if (!config.apiToken) {
      newErrors.apiToken = t('aiConfig.tokenRequired');
    } else if (!validateToken(config.apiToken)) {
      newErrors.apiToken = t('aiConfig.tokenInvalid');
    }
    
    if (!config.provider) {
      newErrors.provider = t('aiConfig.providerRequired');
    }
    
    if (!config.model) {
      newErrors.model = t('aiConfig.modelRequired');
    }
    
    if (!config.endpoint) {
      newErrors.endpoint = t('aiConfig.endpointRequired');
    }
    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSave = async () => {
    if (!validateForm()) {
      return;
    }
    
    setIsSaving(true);
    try {
      const success = saveAIConfig(config);
      if (success) {
        onConfigSaved && onConfigSaved();
        onClose && onClose();
      } else {
        setErrors({ general: t('aiConfig.saveError') });
      }
    } catch (error) {
      console.error('Error saving AI config:', error);
      setErrors({ general: t('aiConfig.saveError') });
    } finally {
      setIsSaving(false);
    }
  };

  const handleReset = () => {
    if (window.confirm(t('aiConfig.resetConfirm'))) {
      setConfig(getAIConfig());
      setErrors({});
    }
  };

  const toggleTokenVisibility = () => {
    setShowToken(!showToken);
  };

  return (
    <div className="ai-config-overlay">
      <div className="ai-config-modal">
        <div className="ai-config-header">
          <h2>{t('aiConfig.title')}</h2>
          <button className="close-btn" onClick={onClose} aria-label="Close">
            ×
          </button>
        </div>
        
        <div className="ai-config-content">
          {errors.general && (
            <div className="error-message">{errors.general}</div>
          )}
          
          <div className="config-form">
            <div className="form-group">
              <label htmlFor="provider">{t('aiConfig.provider')}</label>
              <select
                id="provider"
                name="provider"
                value={config.provider}
                onChange={handleProviderChange}
                className={errors.provider ? 'error' : ''}
              >
                {providers.map(provider => (
                  <option key={provider.id} value={provider.id}>
                    {provider.name}
                  </option>
                ))}
              </select>
              {errors.provider && (
                <div className="field-error">{errors.provider}</div>
              )}
            </div>
            
            <div className="form-group">
              <label htmlFor="model">{t('aiConfig.model')}</label>
              <select
                id="model"
                name="model"
                value={config.model}
                onChange={handleChange}
                className={errors.model ? 'error' : ''}
              >
                {models.map(model => (
                  <option key={model.id} value={model.id}>
                    {model.name}
                  </option>
                ))}
              </select>
              {errors.model && (
                <div className="field-error">{errors.model}</div>
              )}
            </div>
            
            <div className="form-group">
              <label htmlFor="apiToken">{t('aiConfig.apiToken')}</label>
              <div className="token-input-group">
                <input
                  id="apiToken"
                  name="apiToken"
                  type={showToken ? 'text' : 'password'}
                  value={config.apiToken}
                  onChange={handleChange}
                  placeholder={t('aiConfig.tokenPlaceholder')}
                  className={errors.apiToken ? 'error' : ''}
                />
                <button
                  type="button"
                  className="token-visibility-btn"
                  onClick={toggleTokenVisibility}
                  aria-label={showToken ? 'Hide token' : 'Show token'}
                >
                  {showToken ? '👁️' : '👁️‍🗨️'}
                </button>
              </div>
              {errors.apiToken && (
                <div className="field-error">{errors.apiToken}</div>
              )}
              <div className="field-help">
                {t('aiConfig.tokenHelp')}
              </div>
            </div>
            
            <div className="form-group">
              <label htmlFor="endpoint">{t('aiConfig.endpoint')}</label>
              <input
                id="endpoint"
                name="endpoint"
                type="text"
                value={config.endpoint}
                onChange={handleChange}
                className={errors.endpoint ? 'error' : ''}
              />
              {errors.endpoint && (
                <div className="field-error">{errors.endpoint}</div>
              )}
            </div>
            
            <div className="form-group">
              <label htmlFor="maxTokens">{t('aiConfig.maxTokens')}</label>
              <input
                id="maxTokens"
                name="maxTokens"
                type="number"
                min="100"
                max="8000"
                value={config.maxTokens}
                onChange={handleChange}
              />
            </div>
            
            <div className="form-group">
              <label htmlFor="temperature">
                {t('aiConfig.temperature')}: {config.temperature}
              </label>
              <input
                id="temperature"
                name="temperature"
                type="range"
                min="0"
                max="2"
                step="0.1"
                value={config.temperature}
                onChange={handleChange}
              />
            </div>
          </div>
        </div>
        
        <div className="ai-config-footer">
          <button
            type="button"
            className="secondary-btn"
            onClick={handleReset}
            disabled={isSaving}
          >
            {t('aiConfig.reset')}
          </button>
          <div className="footer-spacer"></div>
          <button
            type="button"
            className="secondary-btn"
            onClick={onClose}
            disabled={isSaving}
          >
            {t('aiConfig.cancel')}
          </button>
          <button
            type="button"
            className="primary-btn"
            onClick={handleSave}
            disabled={isSaving}
          >
            {isSaving ? t('aiConfig.saving') : t('aiConfig.save')}
          </button>
        </div>
      </div>
    </div>
  );
};

export default AIConfig;